<template>
  <div id="ww_login"></div>
</template>
<script lang="ts" setup>
import * as ww from '@wecom/jssdk'
const emit = defineEmits(['setIsLogin', 'success'])
import { getTenantId } from '@/utils/auth'
import { useUserStore } from '@/store/modules/user'
import weComConfig from '@/utils/weComConfig'
import * as WeComApiConfigApi from '@/api/wecom/apiconfig'
import axios from 'axios'

const corpIdData = ref(null)
onMounted(() => {
  showPanl()
})
// 初始化登录
const showPanl = async () => {
  axios
    .get(
      import.meta.env.VITE_BASE_URL +
        `/open-api/wecom/corp/get-api-config?corpId=${weComConfig.corpId}`
    )
    .then((res) => {
      if (res.data.code == 0) {
        corpIdData.value = res.data.data
        initLogin()
      } else {
        ElMessage.error(res.data.msg)
      }
    })
}
const initLogin = () => {
  const wwLogin = ww.createWWLoginPanel({
    el: '#ww_login',
    params: {
      login_type: 'ServiceApp',
      appid: weComConfig.appid,
      agentid: corpIdData.value.agentId,
      redirect_uri: 'https://scrm.jzsaas.com',
      state: `UserId:${useUserStore().getUser.id}_TenantId:${getTenantId()}`,
      redirect_type: 'callback' //top:顶层页面跳转 callback:通过onLoginSuccess开发者自行处理跳转  self:登录组件跳转
    },
    // 登录成功
    onLoginSuccess({ code }) {
      console.log('登录成功', code)
      sessionStorage.setItem('weComCode', code)
      emit('success', code)
      emit('setIsLogin', true)
    },
    // 登录失败
    onLoginFail(err) {
      console.log('企业微信登录错误回调', err)
      emit('setIsLogin', false)
    },
    // 获取企业微信桌面端登录状态回调
    onCheckWeComLogin({ isWeComLogin }) {
      console.log('获取企业微信桌面端登录状态回调', isWeComLogin)
      // emit('setIsLogin', isWeComLogin)
    },
    // 打开
    onOpenInWecom(res) {
      console.log(res, '打开企业微信客户端成功回调')
    }
  })
}
</script>
<style scoped lang="scss">
#ww_login {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
